import sqlite3
from sqlite3 import Connection


class DatabaseDriver:
    def __init__(self, db_path: str = "db/goods.db"):
        self.db_path = db_path
        self.connection = False
        if db_path:
            self.conn: Connection = sqlite3.connect(self.db_path)
            self.connection = True

    def close(self):
        self.conn.close()
        self.connection = False

    def update(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            cursor.execute(sql)
            self.conn.commit()
            return self.conn.total_changes
        else:
            raise Exception("数据库连接已关闭！")

    def insert(self, sql: str, log: bool = False):
        return self.update(sql, log)

    def delete(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            cursor.execute(sql)
            self.conn.commit()
            return self.conn.total_changes
        else:
            raise Exception("数据库连接已关闭！")

    def query(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            cursor.execute(sql)
            data = cursor.fetchone()
            if log:
                print("sql execute result:{}".format(data))
            return data
        else:
            raise Exception("数据库连接已关闭！")

    def queryAll(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print("sql execute: {}".format(sql))
            cursor.execute(sql)
            data = cursor.fetchall()
            if log:
                print("sql execute result lengths: {}".format(len(data)))
                for index, d in enumerate(data):
                    print("sql execute result:{}".format(index + 1, d))
            return data
        else:
            raise Exception("数据库连接已关闭！")


if __name__ == "__main__":
    db = DatabaseDriver(db_path="../db/goods.db")
    print(db.queryAll(sql="select * from user where 1 = {}".format(1), log=True))
